/*
 * Copyright 2011 Christoph Ludwig (christoph[at]chludwig.de). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.chludwig.ehumanities.provenance.entities;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

import de.chludwig.ehumanities.provenance.background.ZipArchiveTask;
import de.chludwig.ehumanities.provenance.persistence.ArchivePO;
import de.chludwig.ehumanities.provenance.persistence.StorageArea;

/**
 * 
 */
public class Archive {

  private ArchivePO archivePO;

  private UUID containerId;

  public static Archive archiveWithId(UUID archiveId) {
    return new Archive(archiveId);
  }

  static private ArchivePO archivePOForId(UUID identifier) {
    StorageArea storageArea = new StorageArea();
    return new ArchivePO(storageArea, identifier);
  }

  public Archive(UUID containerId) {
    this.containerId = containerId;
    this.archivePO = archivePOForId(containerId);
    this.archivePO.checkReadWritableArchiveFolder();
  }

  /**
   * @return the containerId
   */
  public UUID getContainerId() {
    return containerId;
  }

  private ArchivePO getArchivePO() {
    return archivePO;
  }

  public boolean zipAvailable() {
    File zipArchiveFile = getArchivePO().getZipFile();
    return (zipArchiveFile.isFile() && zipArchiveFile.canRead());
  }

  public File getZipFile() throws IOException {
    File zipArchiveFile = getArchivePO().getZipFile();
    if (!(zipArchiveFile.isFile() && zipArchiveFile.canRead())) {
      String msg = "cannot read file " + zipArchiveFile.getAbsolutePath();
      throw new IOException(msg, null);
    }
    return zipArchiveFile;
  }

  public void startZipTask(ExecutorService executor) {
    ZipArchiveTask task = getArchivePO().getZipTask();
    executor.submit(task);
  }

  public void sweepIfStale(Date cutoffTimestamp) {
    getArchivePO().sweepIfStale(cutoffTimestamp);
  }

}
